<script setup lang="ts">
import {reactive, ref, onMounted} from 'vue'
import {type CascaderProps, message, Modal, Input} from 'ant-design-vue'
import {ReloadOutlined} from '@ant-design/icons-vue';
import {useRouter} from 'vue-router'
import {joinTeam, listTeamByRecommend, listTeamVoByPage} from "@/api/teamController.ts"
import {addTeamUser} from "@/api/teamUserController.ts";
import {useLoginUserStore} from "@/stores/useLoginUserStore.ts";

// 路由实例
const router = useRouter()
const options: CascaderProps['options'] = ref()
const loginUserStore = useLoginUserStore()

// 搜索参数
const searchParams = reactive({
  current: 1,
  pageSize: 10,
  sortField: 'create_time',
  sortOrder: 'descend',
  searchText: '',
  teamname: '',
  tags: [],
  status: undefined
})

// 格式化时间函数
const formatTime = (timeString) => {
  const date = new Date(timeString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}`;
}

// 队伍列表数据
const teamList = ref([])

// 密码输入模态框相关状态
const passwordModalVisible = ref(false)
const password = ref('')
const currentTeamId = ref(null)

// 总队伍数
const total = ref(0)

// 加载状态
const loading = ref(false);

// 模拟队伍数据
const mockTeams = ref([
  {
    id: 1,
    teamname: '前端开发学习小组',
    description: '一起学习前端技术，交流Vue、React等框架的使用经验',
    avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=team1',
    tags: ['前端开发', 'Vue', 'React'],
    maxPerson: 8,
    currentNum: 5,
    userId: 1,
    status: 0,
    createTime: '2023-11-15 10:30',
    updateTime: '2023-11-15 10:30',
    userVO: {
      username: '技术达人',
      userAvatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=user1'
    }
  },
  {
    id: 2,
    teamname: '算法刷题小队',
    description: '每天一道算法题，提升编程能力，备战面试',
    avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=team2',
    tags: ['算法', '面试', '编程'],
    maxPerson: 6,
    currentNum: 4,
    userId: 2,
    status: 0,
    createTime: '2023-11-14 15:45',
    updateTime: '2023-11-14 15:45',
    userVO: {
      username: '算法大师',
      userAvatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=user2'
    }
  },
  {
    id: 3,
    teamname: '后端开发交流群',
    description: '讨论Java、Spring Boot等后端技术，分享项目经验',
    avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=team3',
    tags: ['后端开发', 'Java', 'Spring Boot'],
    maxPerson: 10,
    currentNum: 7,
    userId: 3,
    status: 0,
    createTime: '2023-11-13 09:15',
    updateTime: '2023-11-13 09:15',
    userVO: {
      username: '后端专家',
      userAvatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=user3'
    }
  },
  {
    id: 4,
    teamname: '全栈开发实战',
    description: '从零开始构建全栈项目，前端+后端+数据库全方位学习',
    avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=team4',
    tags: ['全栈', '实战', '项目'],
    maxPerson: 12,
    currentNum: 6,
    userId: 4,
    status: 1,
    createTime: '2023-11-12 14:20',
    updateTime: '2023-11-12 14:20',
    userVO: {
      username: '全栈工程师',
      userAvatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=user4'
    }
  },
  {
    id: 5,
    teamname: 'AI学习研讨组',
    description: '深度学习、机器学习、人工智能技术研究与实践',
    avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=team5',
    tags: ['人工智能', '机器学习', '深度学习'],
    maxPerson: 8,
    currentNum: 3,
    userId: 5,
    status: 2, // 加密状态
    createTime: '2023-11-11 16:30',
    updateTime: '2023-11-11 16:30',
    userVO: {
      username: 'AI研究员',
      userAvatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=user5'
    }
  }])

// 获取状态文本
const getStatusText = (status: number) => {
  switch (status) {
    case 0:
      return '公开'
    case 1:
      return '加密'
    case 2:
      return '私有'
    default:
      return '公开'
  }
}

// 获取状态颜色
const getStatusColor = (status: number) => {
  switch (status) {
    case 0:
      return 'green'
    case 1:
      return 'orange'
    case 2:
      return 'blue'
    default:
      return 'default'
  }
}

// 搜索队伍
const doSearch = () => {
  searchParams.current = 1
  fetchTeamList()
}

// 重置筛选条件
const resetFilters = () => {
  searchParams.searchText = ''
  searchParams.teamname = ''
  searchParams.tags = []
  searchParams.status = undefined
  searchParams.current = 1
  fetchTeamList()
}

// 获取队伍列表
const fetchTeamList = async (isRefresh: boolean = false) => {
  loading.value = true;
  try {
    const res = await listTeamByRecommend({
      ...searchParams,
      isRefresh: isRefresh
    })
    if (res.data.code === 0 && res.data.data) {
      teamList.value = res.data.data.records
      total.value = res.data.data.total
      console.log('获取队伍列表成功')
    } else {
      message.error('获取队伍列表异常，请稍后重试')
    }
  } catch (error) {
    console.error('获取队伍列表异常：', error)
    message.error('获取队伍列表异常，请稍后重试')
  } finally {
    loading.value = false;
  }
}

// 处理分页变化
const handlePaginationChange = (page: number) => {
  searchParams.current = page
  fetchTeamList()
}

// 处理每页显示数量变化
const handlePageSizeChange = (current: number, pageSize: number) => {
  searchParams.current = current
  searchParams.pageSize = pageSize
  fetchTeamList()
}

// 跳转到队伍详情页
const goToTeamDetail = (teamId: number) => {
  router.push(`/team/${teamId}`)
}

// 加入队伍函数
const doJoinTeam = async (teamId: number, e: MouseEvent) => {
  // 阻止事件冒泡，避免触发卡片的点击事件
  if (e) {
    e.stopPropagation();
  }

  // 找到当前队伍信息
  const team = teamList.value.find(t => t.id === teamId);

  if (team && team.status === 1) {
    // 如果队伍是加密的，显示密码输入框
    currentTeamId.value = teamId;
    password.value = '';
    passwordModalVisible.value = true;
  } else {
    const res = await joinTeam({
      teamId: teamId,
      userId: loginUserStore.loginUser.id,
      password: password.value
    })
    if (res.data.code === 0 && res.data.data) {
      message.success('加入成功')
      // 跳转到队伍详情页
      goToTeamDetail(teamId)
    } else {
      message.error('加入失败，' + res.data.message)
    }
  }


}

// 跳转到创建队伍页面
const goToCreateTeam = () => {
  router.push('/team/add')
}

// 获取技能选项
const getTeachAndLearnOptions = async () => {
  try {
    // 模拟数据
    options.value = [
      {
        value: '前端开发',
        label: '前端开发',
        children: [
          {value: 'HTML/CSS', label: 'HTML/CSS'},
          {value: 'JavaScript', label: 'JavaScript'},
          {value: 'Vue', label: 'Vue'},
          {value: 'React', label: 'React'},
          {value: 'Angular', label: 'Angular'}
        ]
      },
      {
        value: '后端开发',
        label: '后端开发',
        children: [
          {value: 'Java', label: 'Java'},
          {value: 'Python', label: 'Python'},
          {value: 'Node.js', label: 'Node.js'},
          {value: 'Spring Boot', label: 'Spring Boot'},
          {value: 'Django', label: 'Django'}
        ]
      },
      {
        value: '算法与数据结构',
        label: '算法与数据结构',
        children: [
          {value: '排序算法', label: '排序算法'},
          {value: '动态规划', label: '动态规划'},
          {value: '图算法', label: '图算法'},
          {value: '数据结构', label: '数据结构'}
        ]
      }
    ]
  } catch (error) {
    console.error('获取选项失败：', error)
    message.error('获取选项失败，请稍后重试')
  }
}


// 确认加入队伍（带密码）
const handleConfirmJoin = async () => {
  // 这里仅实现模态框的关闭逻辑，不需要实现加入队伍的具体功能
  passwordModalVisible.value = false;

  const res = await joinTeam({
    teamId: currentTeamId.value,
    userId: loginUserStore.loginUser.id,
    password: password.value
  })
  password.value = '';
  if (res.data.code === 0 && res.data.data) {
    message.success('加入成功')
    // 跳转到队伍详情页
    goToTeamDetail(currentTeamId)
  } else {
    message.error('加入失败，' + res.data.message)
  }
}

// 取消加入
const handleCancelJoin = () => {
  passwordModalVisible.value = false;
  password.value = '';
  currentTeamId.value = null;
}

//加入队伍
// const handleJoinTeam = async (teamId) => {
//   const res = await joinTeam({
//     teamId: teamId,
//     userId: loginUserStore.loginUser.id,
//     password:
//
//
//   })
// }

onMounted(() => {
  // getTeachAndLearnOptions()
  fetchTeamList()
})
</script>
<template>
  <div id="TeamPage">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="title">厚米组队</h2>
      <p class="subtitle">寻找志同道合的学习伙伴，一起组队学习</p>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-filter-container">
      <a-form layout="inline" :model="searchParams" @submit="doSearch">
        <a-form-item label="搜索">
          <a-input
              v-model:value="searchParams.searchText"
              placeholder="综合搜索"
              allow-clear
          />
        </a-form-item>
        <a-form-item
            label="队伍名称"
            name="teamname">
          <a-input
              v-model:value="searchParams.teamname"
              placeholder="输入队伍名称"
              allow-clear
          />
        </a-form-item>
        <a-form-item
            label="标签"
            name="tags">
          <a-select
              v-model:value="searchParams.tags"
              mode="tags"
              style="width: 250px"
              placeholder="请输入博客标签，按下回车确认"
              :open="false"
          />
<!--          <a-cascader-->
<!--              v-model:value="searchParams.tags"-->
<!--              style="width: 200px"-->
<!--              multiple-->
<!--              max-tag-count="responsive"-->
<!--              :options="options"-->
<!--              placeholder="选择队伍标签"-->
<!--          />-->
        </a-form-item>
        <a-form-item
            label="状态"
            name="status">
          <a-select v-model:value="searchParams.status" placeholder="选择队伍状态" allow-clear>
            <a-select-option value="0">公开</a-select-option>
            <a-select-option value="1">加密</a-select-option>
            <a-select-option value="2">私有</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item>
          <a-button type="primary" html-type="submit">搜索</a-button>
        </a-form-item>

        <a-form-item>
          <a-button @click="resetFilters">重置</a-button>
        </a-form-item>

        <a-form-item class="create-team-button">
          <a-button type="primary" @click="goToCreateTeam">
            创建队伍
          </a-button>
        </a-form-item>
      </a-form>
    </div>

    <!-- 队伍列表 -->
    <div class="team-results">
      <div class="results-header">
        <h3>队伍列表</h3>
        <div style="display: flex; align-items: center; gap: 15px;">
          <span class="results-count">{{ total }} 个队伍</span>
          <a-button @click="fetchTeamList(true)" :loading="loading" size="small">
            <template #icon>
              <ReloadOutlined/>
            </template>
            刷新
          </a-button>
        </div>
      </div>

      <!-- 列表为空时显示 -->
      <div v-if="!teamList.length" class="empty-state">
        <a-empty description="暂无队伍"/>
        <p class="empty-tips">尝试调整搜索条件或创建一个新队伍</p>
      </div>

      <!-- 队伍卡片列表 -->
      <div v-else class="team-cards-grid">
        <div v-for="team in teamList" :key="team.id" class="team-card" @click="goToTeamDetail(team.id)">
          <!-- 队伍头像和信息 -->
          <div class="team-info">
            <a-avatar :size="64" :src="team.avatar" class="team-avatar"/>
            <div class="team-basic">
              <h4 class="team-name">{{ team.teamname }}</h4>
              <div class="team-meta">
                <span class="team-creator">队长：{{ team.userVO.username }}</span>
                <span class="team-count">{{ team.memberVOs.length }}/{{ team.maxPerson }}</span>
              </div>
            </div>
          </div>

          <!-- 队伍描述 -->
          <p class="team-description">{{ team.description }}</p>

          <!-- 队伍标签 -->
          <div class="team-tags">
            <a-tag v-for="tag in team.tags" :key="tag" color="blue">
              {{ tag }}
            </a-tag>
            <a-tag :color="getStatusColor(team.status)">{{ getStatusText(team.status) }}</a-tag>
          </div>

          <!-- 创建时间 -->
          <div class="team-time">
            创建时间：{{ formatTime(team.createTime) }}
          </div>

          <!-- 操作按钮 -->
          <div class="team-actions">
            <a-button @click.stop="goToTeamDetail(team.id)" style="margin-right: 8px;">
              查看详情
            </a-button>
            <a-button type="primary" @click.stop="doJoinTeam(team.id, $event)">
              加入队伍
            </a-button>
          </div>
        </div>
      </div>

      <!-- 分页控件 -->
      <div v-if="teamList.length" class="pagination-container">
        <a-pagination
            v-model:current="searchParams.current"
            v-model:pageSize="searchParams.pageSize"
            :pageSize-options="['10', '20', '50']"
            :total="total"
            showSizeChanger
            showQuickJumper
            :showTotal="(total) => `共 ${total} 条数据`"
            @change="handlePaginationChange"
            @showSizeChange="handlePageSizeChange"
        />
      </div>

      <!-- 密码输入模态框 -->
      <a-modal
          v-model:visible="passwordModalVisible"
          title="加入加密队伍"
          @ok="handleConfirmJoin"
          @cancel="handleCancelJoin"
          okText="确认"
          cancelText="取消"
      >
        <div style="margin-bottom: 16px;">
          <p>该队伍需要密码才能加入，请输入密码：</p>
        </div>
        <a-input
            v-model:value="password"
            type="password"
            placeholder="请输入队伍密码"
            allow-clear
            style="width: 100%;"
        />
      </a-modal>
    </div>
  </div>
</template>

<style scoped>
#TeamPage {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.title {
  font-size: 28px;
  font-weight: bold;
  color: #1890ff;
  margin-bottom: 10px;
}

.subtitle {
  font-size: 16px;
  color: #666;
}

.search-filter-container {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}


.team-results {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.results-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.results-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: bold;
}

.results-count {
  color: #666;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
}

.empty-tips {
  margin-top: 10px;
  color: #999;
}

.team-cards-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(360px, 1fr));
  gap: 20px;
}

.team-card {
  padding: 20px;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  background: white;
}

.team-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

.team-info {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.team-avatar {
  margin-right: 16px;
}

.team-basic {
  flex: 1;
}

.team-name {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.team-meta {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  color: #666;
}

.team-description {
  margin: 0 0 16px 0;
  font-size: 14px;
  color: #666;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.team-tags {
  margin-bottom: 16px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.team-time {
  font-size: 12px;
  color: #999;
  text-align: right;
  margin-bottom: 16px;
}

.team-actions {
  display: flex;
  justify-content: flex-end;
}

.team-actions .a-button {
  margin-left: 8px;
}

.pagination-container {
  margin-top: 30px;
  display: flex;
  justify-content: flex-end;
}

.create-team-button {
  margin-left: auto !important;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .team-cards-grid {
    grid-template-columns: 1fr;
  }

  .search-filter-container .a-form-inline {
    flex-direction: column;
  }

  .search-filter-container .a-form-item {
    margin-bottom: 15px;
    width: 100%;
  }

  .create-team-button {
    margin-left: 0 !important;
  }
}
</style>
